// import { showFailToast, showSuccessToast, showLoadingToast } from "vant";

export function getCataloguePath(path) {
  let pos1 = path.lastIndexOf('/');
  let pos2 = path.lastIndexOf('\\');
  let pos = Math.max(pos1, pos2);
  if (pos < 0) {
    return path;
  }
  else {
    return path.substring(0, pos);
  }
}
let dev = process.env.NODE_ENV == "development"; // 是否开发模式 开发模式使用模拟数据
let regex = /Android|webOS|iPhone|iPod|iPad|BlackBerry/i;
let phoneFlag = regex.test(navigator.userAgent); // 是否为移动端

export function vrvInit() {
  /* global vrv */
  vrv.init({
    debug: false,
  });
}

export function ready() {
  return new Promise((resolve, reject) => {
    vrv.ready(function () {
      // init信息验证后会执行ready方法，所有接口调用都必须在init接口获得结果之后，init是一个客户端的异步操作，
      //所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。
      //对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。

      //切换H5应用横竖屏模式
      //需满足条件 JSSDK版本需要3.9.9及以上，豆豆服务器版本6.0.1.6以上
      vrv.jssdk.changeAppScreenOrientation({
        appSign: "aflow",
        orientation: "horizontal", //展示类型，默认为vertical horizontal 横屏模式，vertical竖屏模式
        success: function (res) {
          let resultCode = res.resultCode;
          console.log("changeAppScreenOrientation", res);
        },
      });
      resolve();
    });
  });
}


/*
  保存图片
  将图片保存到手机或电脑中，支持图片链接和图片流两种方式。
  base64格式图片，需要去掉前缀，只保留“base64,”后面的字符串
*/
export function saveImagetoSysAlbum(imgData, filename) {
  return new Promise((resolve, reject) => {
    // 不支持PC
    if (!phoneFlag) {
      // showFailToast("您的PC客户端暂不支持！");
      reject();
      return;
    }
    vrv.jssdk.saveImagetoSysAlbum({
      type: 2, // 图片类型，1-图片链接，2-图片流
      image: imgData, // base64格式
      success: function (res) {
        let resultCode = res.resultCode;
        if (resultCode == 0) {
          resolve(res);
        } else {
          // 失败
          // showFailToast("保存失败");
          reject(res);
        }
      },
    });
  });
}

/*
  获取下级组织机构和用户
  返回组织机构列表（组织机构id和组织机构名称），用户列表（用户名称和用户头像）
*/
export function getOrganization() {
  return new Promise((resolve, reject) => {
    vrv.jssdk.getOrganization({
      orgId: "0",
      success(res) {
        let organization = res.organization;
        let staff = res.staff;
        resolve(res);
      },
    });
  });
}

/*
  查询用户群列表
  获取用户所加入的群列表，包含群头像、群名称、群名称首字母等
*/
export function getGroupList() {
  return new Promise((resolve, reject) => {
    if (dev) {
      let res = [
        {
          groupNameInitial: "Z",
          serverName: "ecs",
          groupName: "总指挥部",
          groupID: "21265121857",
          groupPortraitURL: "",
        },
        {
          groupNameInitial: "A",
          serverName: "ecs",
          groupName: "A群",
          groupID: "21265122793",
          groupPortraitURL: "",
        },
        {
          groupNameInitial: "B",
          serverName: "ecs",
          groupName: "B群",
          groupID: "21265122794",
          groupPortraitURL: "",
        },
        {
          groupNameInitial: "C",
          serverName: "ecs",
          groupName: "C群",
          groupID: "21265122795",
          groupPortraitURL: "",
        },
        {
          groupNameInitial: "Z",
          serverName: "ecs",
          groupName: "智慧报表临时讨论群",
          groupID: "21265122826",
          groupPortraitURL: "",
        },
        {
          groupNameInitial: "E",
          serverName: "ecs",
          groupName: "E群",
          groupID: "21265123292",
          groupPortraitURL: "",
        },
        {
          groupNameInitial: "F",
          serverName: "ecs",
          groupName: "F群",
          groupID: "21265123293",
          groupPortraitURL: "",
        },
      ];
      setTimeout(() => {
        resolve(res);
      }, 500);
      return;
    }
    vrv.jssdk.getGroupList({
      success: function (res) {
        let resultCode = res.resultCode;
        let groupsInfo = res.groupsInfo;
        resolve(groupsInfo);
      },
    });
  });
}

// 查询群内群成员列表
export function getGroupMembers(userId) {
  return new Promise((resolve, reject) => {
    if (dev) {
      let member = [];
      switch (userId) {
        case "21265121857":
          member = [
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "廖杰",
              memberID: "21256832673",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "省厅值班员1",
              memberID: "21256832674",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "省厅值班员2",
              memberID: "21256832675",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "南宁市值班员",
              memberID: "21256832676",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "胡刘雨",
              memberID: "21256834681",
            },
          ];
          break;
        case "21265122793":
          member = [
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "毛有余",
              memberID: "21256833207",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "test1",
              memberID: "21256833210",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "f002",
              memberID: "21256833211",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "盛达腾",
              memberID: "21256833683",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "胡刘雨",
              memberID: "21256834681",
            },
          ];
          break;
        case "21265122794":
          member = [
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "毛有余",
              memberID: "21256833207",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "test1",
              memberID: "21256833210",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "于立佳",
              memberID: "21256833724",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "郑宁",
              memberID: "21256834175",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "魏建军",
              memberID: "21256834176",
            },
          ];
          break;
        case "21265122795":
          member = [
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "李明杰",
              memberID: "21256834177",
            },
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "杨丹",
              memberID: "21256834178",
            },
          ];
          break;
        case "21265122826":
          member = [
            {
              memberNameInitial: "#",
              serverName: "ecs",
              memberName: "常兴",
              memberID: "21256834183",
            },
          ];
          break;
      }
      setTimeout(() => {
        resolve(member);
      }, 500);
      return;
    }
    //vrv.jssdk.getGroupList({
    //  success: function (res) {
    //    console.log(">>>", res.groupsInfo);
    //    var resultCode = res.resultCode;
    //    var groupsInfo = res.groupsInfo;
    //  },
    //});
    vrv.jssdk.getGroupMembers({
      groupID: userId,
      success: function (res) {
        let resultCode = res.resultCode;
        let members = res.members;
        resolve(res.members);
      },
    });
  });
}
/*
  查询用户好友列表信息
 */
export function getFriendList() {
  return new Promise((resolve, reject) => {
    if (dev) {
      let res = [
        {
          buddyID: "21256834681",
          buddyName: "胡刘雨",
          portraitURL: "https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg",
          buddyNameInitial: "H",
        },
        {
          buddyNameInitial: "Y",
          serverName: "ecs",
          buddyName: "杨昌华",
          buddyID: "21256834213",
        },
        {
          buddyNameInitial: "A",
          serverName: "ecs",
          buddyName: "ay",
          buddyID: "21256834674",
        },
        {
          buddyNameInitial: "L",
          serverName: "ecs",
          buddyName: "刘宇鑫",
          buddyID: "21256834680",
        },
      ];
      resolve(res);
    } else {
      vrv.jssdk.getContactList({
        success: function (res) {
          let contacts = res.contacts;
          resolve(contacts);
        },
      });
    }
  });
}

/*
  查询下级组织机构和用户
*/
export function getOrganizationList(id) {
  return new Promise((resolve, reject) => {
    vrv.jssdk.getOrganization({
      orgId: id || "0",
      success(res) {
        let organization = res.organization;
        let staff = res.staff;
        resolve(res);
      },
    });
  });
}

/*
  根据组织机构ID查询组织机构信息。
*/
export function getOrganizationInfo(id) {
  return new Promise((resolve, reject) => {
    vrv.jssdk.getOrgInfo({
      orgId: id || "0",
      success(res) {
        let orgName = res.orgName;
        let orgCode = res.orgCode;
        resolve(res);
      },
    });
  });
}


// 选择本地文件  附件上传
export function getLocalFiles(size = 10) {
  registerProgressNotice();
  return new Promise((resolve, reject) => {
    vrv.jssdk.getLocalFiles({
      size: size, // 最多选择文件的个数，最大值 10，可为空，默认 10
      type: 10020,
      success(r) {
        if (r.resultCode == 0) {
          // showSuccessToast("上传完成！");
          resolve(r);
        } else if (r.resultCode == -1) {
          // showFailToast("上传失败！");
          reject(r);
        } else if (r.resultCode == -2) {
          reject(r);
        }
      },
    });
  });
}

// 选择本地文件  附件上传 无需上传成功提示版
export function getLocalFilesNoTips(size = 10) {
  registerProgressNotice();
  return new Promise((resolve, reject) => {
    // 本地开发模式
    vrv.jssdk.getLocalFiles({
      size: size, // 最多选择文件的个数，最大值 10，可为空，默认 10
      type: 10020,
      success(r) {
        if (r.resultCode == 0) {
          // showSuccessToast('上传完成！')
          resolve(r);
        } else if (r.resultCode == -1) {
          // showFailToast("上传失败！")
          reject(-1);
        } else if (r.resultCode == -2) {
          reject(-2);
        }
      },
    });
  });
}


// 打开文件
export function openFileURL(url, name) {
  return new Promise((resolve, reject) => {
    // 判断当前设备是否为移动端-移动端直接打开该文件查看
    if (phoneFlag) {
      vrv.jssdk.openFileURL({
        url: url,
        name: name, // 需要界面上显示的文件名
        success: (res) => {
          // console.log(res, "打开链接成功");
          resolve(res);
        },
      });
    } else {
      if (!!vrv.client) {
        // PC端-需要先下载该文件后再打开该文件查看
        // showLoadingToast({
        //   duration: 0,
        //   forbidClick: true,
        //   message: "文件下载中",
        // });
        vrv.jssdk.downloadFile({
          type: 1,
          url: url,
          fileName: name,
          savePath: "LinkdoodSDK/collect",
          encryptKey: "", //密钥，不加密的文件可以不传，不为空就是加密文件
          success: function (res) {
            let resultCode = res.resultCode;
            let resultPath = res.resultPath;
            // 对返回的文件路径做处理，只保留目录路径
            const catalogue = getCataloguePath(resultPath);
            if (resultCode == -1) {
              // 失败
              // showFailToast("下载失败！");
              reject();
            } else {
              // showSuccessToast("文件下载完成！请稍等...");
              // 文件下载成功后，打开该文件
              vrv.jssdk.openFilePath({
                type: 2,
                path: catalogue,
                success: function (res1) {
                  let resultCode = res1.resultCode;
                  if (resultCode == -1) {
                    // showFailToast("该文件无法打开！");
                    // 失败
                    reject();
                  } else {
                    resolve(res1);
                  }
                },
              });
            }
          },
        });
      }else {
        const a = document.createElement("a");
        a.href = url;
        a.download = name; // 设置文件名
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      }
    }
  });
}

//拍照上传
export function getPhotograph() {
  return new Promise((resolve, reject) => {
    if (dev) {
      let r = {
        // r的数据类型   模拟数据
        mFileName: ["测试1.png"],
        mPhotoPath: [
          "https://fastly.jsdelivr.net/npm/@vant/assets/apple-3.jpeg",
        ],
        resultCode: 0, // 0 成功  -1 失败   -2 取消
      };
      resolve(r);
    } else {
      vrv.jssdk.takePhoto({
        upload: true,
        compress: true,
        compressPercent: 50,
        success: function (res) {
          let resultCode = res.resultCode;
          if (res.resultCode === 0) {
            // showSuccessToast("上传成功！");
            resolve(res);
          } else if (res.resultCode === -1) {
            // showFailToast("失败");
            reject();
          } else if (res.resultCode === -2) {
            reject();
          }
        },
      });
    }
  });
}

//上传本地照片
export function getLocalPhotos() {
  return new Promise((resolve, reject) => {
    vrv.jssdk.getLocalPhotos({
      size: 5,
      upload: true,
      compress: true,
      compressPercent: 50,
      success: function (res) {
        let resultCode = res.resultCode;
        if (res.resultCode === 0) {
          // showSuccessToast("上传成功！");
          resolve(res);
        } else if (res.resultCode === -1) {
          reject();
          // showFailToast("上传失败！");
        } else if (res.resultCode === -2) {
          reject();
        }
      },
    });
  });
}


